<template>
  <div>
    <mheader></mheader>
    <div class="card">
      <Card style="width: 400px;">
        <Tabs @on-click="changeTab">
          <TabPane label="用户登录" name="login">
            <div>
              <Form ref="loginForm" :model="loginForm" :rules="loginRule" :label-width="80">
                <FormItem label="登录账号" prop="loginId">
                  <Input type="text" v-model="loginForm.loginId"></Input>
                </FormItem>
                <FormItem label="密码" prop="passwd">
                  <Input type="password" v-model="loginForm.passwd"></Input>
                </FormItem>
                <FormItem>
                  <Button shape="circle" @click="handleLogin('loginForm')" style="width: 40%; font-size: 15px; background-color: #fd6857; color: #fff;">登录
                  </Button>
                </FormItem>
              </Form>
            </div>
          </TabPane>
          <TabPane label="用户注册" name="register">
            <div v-show="to === 'register'" transfer>
              <Form ref="registerForm" :model="registerForm" :rules="registerRule" :label-width="80">
                <FormItem label="登录账号" prop="loginId">
                  <Input type="text" v-model="registerForm.loginId"></Input>
                </FormItem>
                <FormItem label="昵称" prop="nickname">
                  <Input type="text" v-model="registerForm.nickname"></Input>
                </FormItem>
                <FormItem label="手机号码" prop="phone">
                  <Input type="text" v-model="registerForm.phone"></Input>
                </FormItem>
                <FormItem label="密码" prop="password">
                  <Input type="password" v-model="registerForm.password"></Input>
                </FormItem>
                <FormItem label="确认密码" prop="passwdCheck">
                  <Input type="password" v-model="registerForm.passwdCheck"></Input>
                </FormItem>
                <FormItem label="验证码" prop="verifyC">
                  <Row style="height: 36px;">
                    <Col span="11">
                    <Input type="text" v-model="registerForm.verifyC"></Input>
                    </Col>
                    <Col span="2">&nbsp;</Col>
                    <Col span="11">
                    <img :src="vcodeSrc" alt="code" @click="changeCode">
                    <canvas width="100" height="40" ref="verifyCanvas" style="display: none;"></canvas>
                    </Col>
                  </Row>
                </FormItem>
                <FormItem>
                  <Button shape="circle" @click="handleRegister" style="width: 48%; font-size: 15px; background-color: #fd6857; color: #fff;">
                    同意协议并注册
                  </Button>
                  <a href="/#" style="margin-left:20px;text-decoration:underline;color:#959ca8;"
                     target="_blank">注册协议</a>
                </FormItem>
              </Form>
            </div>
          </TabPane>
        </Tabs>
      </Card>
    </div>

    <mfooter></mfooter>
  </div>
</template>

<style lang="css" scoped>
.card {
  margin: 20px 0 20px 35%;
}
</style>

<script>
  import vcode from '@/common/vcode';
  import mheader from "@/components/mheader";
  import mfooter from "@/components/mfooter";
  import Cookies from 'js-cookie';

  export default {
    name: "login",
    components: {
      mheader,
      mfooter,
    },
    data() {
      const checkExistLoginId = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入登录账号'));
        } else {
          this.$axios({
            method: 'get',
            url: '/api/checkId',
            params: {
              loginId: value,
            }
          }).then(res => {
            console.log(res.data)
            if (res.data.status !== 0) {
              callback(new Error('账号已经存在！'))
            } else {
              callback()
            }
          });
        }
      };
      const validatePhone = (rule, value, callback) => {
        const phoneRe = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (value === '') {
          callback(new Error('请输入电话号码'));
        } else {
          if (!phoneRe.test(value)) {
            callback(new Error('请输入正确格式的电话号码'));
          } else {
            callback();
          }
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.registerForm.passwdCheck !== '') {
            // 对第二个密码框单独验证
            this.$refs.registerForm.validateField('passwdCheck');
          }
          callback();
        }
      };
      const validatePassCheck = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入确认密码'));
        } else if (value !== this.registerForm.password) {
          callback(new Error('确认密码与密码不统一!'));
        } else {
          callback();
        }
      };
      const validateCode = (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('请输入验证码'));
        } else if (!this.validCode(value)) {
          callback(new Error('验证码不正确'));
        } else {
          callback();
        }
      };

      return {
        to: '',
        vcodeSrc: '',
        vcode: [],
        loginForm: {
          loginId: '',
          passwd: ''
        },
        loginRule: {
          loginId: [
            { required: true, type: 'string', message: '请输入登录账号', trigger: 'blur' }
          ],
          passwd: [
            { required: true, type: 'string', message: '请输入密码', trigger: 'blur' }
          ]
        },
        registerForm: {
          loginId: '',
          nickname: '',
          phone: '',
          password: '',
          passwdCheck: '',
          verifyC: ''
        },
        registerRule: {
          loginId: [
            {required: true, validator: checkExistLoginId, trigger: 'blur'}
          ],
          nickname: [
            { required: true, type: 'string', message: '请输入用户名', trigger: 'blur' }
          ],
          phone: [
            { required: true, validator: validatePhone, trigger: 'blur' }
          ],
          password: [
            { required: true, validator: validatePass, trigger: 'blur' }
          ],
          passwdCheck: [
            { required: true, validator: validatePassCheck, trigger: 'blur' }
          ],
          verifyC: [
            { required: true, validator: validateCode, trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      handleLogin() {
        this.$refs['loginForm'].validate((valid) => {
          if (valid) {
            this.$axios({
              method: 'post',
              url: '/api/login',
              data: {
                loginId: this.loginForm.loginId,
                password: this.loginForm.passwd,
              }
            }).then(res => {
              if (res.data.status === -1){
                this.$Message.error('登录失败!');
              } else {
                this.$Message.success('登陆成功!');
                Cookies.set('customer', res.data);
                this.$router.push({
                 path: '/'
                });
              }
            }).catch(error => {
              this.$Message.error('登录失败!');
            });
          } else {
            this.$Message.error('登录失败!');
          }
        })
      },
      handleRegister() {
        this.$refs['registerForm'].validate((valid) => {
          if (valid) {
            this.$axios({
              method: 'post',
              url: '/api/register',
              data: {
                registerData: this.registerForm
              }
            }).then(res => {
              this.$Message.success('注册成功!');
            }).catch(error => {
              this.$Message.error('注册失败!');
            });
          } else {
            this.$Message.error('注册失败!');
          }
        })
      },
      handleSuccess() {

      },
      validCode(value) {
        return this.vcode.join('').toLowerCase() === value.toLowerCase();
      },
      changeCode() {
        this.vcodeSrc = vcode.drawCode(this.$refs.verifyCanvas);
        this.vcode = vcode.code;
      },
      changeTab(name) {
        this.to = name;
      }
    },
    mounted() {
      this.changeCode();
    }
  }
</script>
